<template>
  <el-dialog
    title="导入员工"
    :visible="value"
    width="40%"
    @close="close"
  >
    <template #default>
      <div class="IDcontent">
        <svg-icon icon-class="eye-open" />
        <el-button :loading="downloading" type="text" @click="downloadTemplate">下载excel模版</el-button>
        <el-button type="text" @click="$refs.file.click()">点击上传</el-button>
        <input ref="file" type="file" accept=".xlsx" :style="{ display: 'none' }" @change="handleFileChange">
      </div>
    </template>
    <template #footer>
      <el-button size="mini" type="primary" @click="close">取 消</el-button>
    </template>
  </el-dialog>
</template>

<script>
import { getTemplateData, importEmployee } from '@/api/employee'
import { saveAs } from 'file-saver'
export default {
  name: 'ImportDialog',
  props: {
    value: {
      type: Boolean,
      default: false
    }
  },
  data() {
    return {
      downloading: false
    }
  },
  methods: {
    close() {
      this.$emit('input', false)
    },
    async downloadTemplate() {
      if (this.downloading) return
      try {
        this.downloading = true
        const res = await getTemplateData()
        saveAs(res, '员工导入模版.xlsx')
      } catch (error) {
        console.log(error)
      } finally {
        this.downloading = false
      }
    },
    async handleFileChange(e) {
      const a = e.target.files
      //   console.log(a)
      try {
        await importEmployee(a[0])
        // 关对话框
        this.close()
        // 给用户提示
        this.$message.success('导入成功')
        // 刷新列表
        this.$emit('refresh')
      } finally {
        this.$refs.file.value = ''// 清空input
      }
    }
  }
}
</script>

<style scoped lang="scss">
    .IDcontent{
        display: flex;
        flex-direction: column;
        align-items: center;
    }
</style>
